package com.csp.base.service.impl;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.util.List;

import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.csp.base.constant.JOB_HISTORY_RUN_STATUS;
import com.csp.base.mapper.JobRunHistoryMapper;
import com.csp.base.model.JobRunHistory;
import com.csp.base.service.JobRunHistoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class JobRunHistoryServiceImpl implements JobRunHistoryService{
	private String servHost;
	@Value("${server.port}")
	private String servPost;
	
	@Autowired
	JobRunHistoryMapper jobRunHistoryMapper;
	
	public JobRunHistoryServiceImpl() {
		try {
			servHost = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			servHost="127.0.0.1";
		}
		this.servPost = "servPost";
	}

	@Override
	public void recordRunHistoty(JobExecutionContext context,Exception jobException) {
    	String runStatus=JOB_HISTORY_RUN_STATUS.SUCCESS;
    	String message="";
    	if (jobException!=null) {
    		runStatus=JOB_HISTORY_RUN_STATUS.FAILED;
    		message =jobException.getMessage();
		}
    	JobKey key = context.getJobDetail().getKey();
        String jobName = key.getName();
        String group = key.getGroup();
        JobDetail jobDetail = context.getJobDetail();
        Class<? extends Job> jobClass = jobDetail.getJobClass();
        JobRunHistory history=new JobRunHistory();
        history.setRunStatus(runStatus);
        history.setJobName(jobName);
        history.setJobGroupName(group);
        history.setJobClassName(jobClass.getName());
        history.setMessage(message);
        history.setCreateTime(new Timestamp(System.currentTimeMillis()));
        history.setHost(servHost);
        history.setPort(servPost);
        jobRunHistoryMapper.insertJobRunHistory(history);
	}

	@Override
	public PageInfo<JobRunHistory> getJobRunHitoryList(int pageNum, int pageSize,String jobName,String jobGroupName,String jobClassName) {
		PageHelper.startPage(pageNum, pageSize);
		List<JobRunHistory> list =jobRunHistoryMapper.findJobRunHitoryList(jobName,jobGroupName,jobClassName);
		PageInfo<JobRunHistory> page = new PageInfo<JobRunHistory>(list);
		return page;
	}
	
}
